#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@fileName     : message.py
@description  : 企业微信消息处理
@time         : 2021年04月10日 10:02
@author       : WeiTingjun
@versions     : 1.0
'''
import requests
import json
import time
import datetime

from log import logger
from .config import WechatConfigObject


class WeCom(WechatConfigObject):
    def __init__(self):
        super(WeCom, self).__init__()
        self.update_overdue_token()
        self.is_text_msg = False  # 文本消息
        self.is_markdown_msg = False  # markdown消息，微信不支持，企业微信支持
        self.is_textcard_msg = False  # 文本卡片消息
        self.message = {"title": "",
                        "detail": ""}

    def send_msg(self, to_users=None):
        """
        发送消息
        """
        url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(self.access_token)
        request_body = {
            "touser": to_users if to_users else self.to_users,  # 传了用户取传的，没传取config.ini
            "toparty": "",
            "totag": "",
            "msgtype": "",
            "agentid": self.agent_id,
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }
        today = datetime.datetime.today()
        now = today.strftime('%Y年%m月%d日 %H:%M')
        if self.is_text_msg:
            request_body['msgtype'] = 'text'
            request_body.setdefault('text', {"content": self.message.get('title') + '\n' + self.message.get('detail')})
        elif self.is_markdown_msg:
            request_body['msgtype'] = 'markdown'
            request_body.setdefault('markdown', {
                "content": "><font color=\"info\">{0}</font>\n><font color=\"comment\">{1}</font>\n><font color=\"warning\">{2}</font>".format(
                    self.message.get('title'), now, self.message.get('detail'))})
        elif self.is_textcard_msg:
            request_body['msgtype'] = 'textcard'
            textcardvalue = {
                "title": self.message.get('title'),
                "description": "<div class=\"gray\">{}</div><br><div class=\"highlight\">{}</div>".format(now,
                                                                                                          self.message.get(
                                                                                                              'detail')),
                "url": "http://123.57.138.224:5000/list",
                "btntxt": "更多待办"}
            request_body.setdefault('textcard', textcardvalue)
        else:
            return "未指定消息类型"
        body_json = json.dumps(request_body)
        res = requests.post(url, data=body_json)
        logger.info("调用企业微信的返回结果：{}".format(res.text))

    def update_overdue_token(self):
        '''
            更新配置文件的过期token
        '''
        time_apart = int(time.time()) - int(self.token_indate)
        if time_apart >= 7200:  # 判断配置文件的access_token是否过期
            self.access_token = AccessToken(corpid=self.corp_id,  # 调用企业微信，获取access_token
                                            secret=self.secret).get_access_token()
            expires_in = str(int(time.time()))
            self.update_section(node_section='AccessToken',
                                corpid=self.corp_id,
                                agentid=self.agent_id,
                                secret=self.secret,
                                userid=self.to_users,
                                access_token=self.access_token,
                                expires_in=expires_in)  # 更新token


class AccessToken(object):
    """
    获取企业微信接口token
    """

    def __init__(self, corpid='wwd24c93762fe9ebed', secret='hmBQ8tYIxePA9NzuVQ2gJW1oBAz3GyStrgdu-xXqmxY'):
        '''
        :param corpid: 企业id
        :param secret:  应用secret
        '''
        self.corpid = corpid
        self.secret = secret

    def get_access_token(self):
        '''
        获取应用的access_token，每个应用需要单独获取access_token
        :return: 返回access_token字符串
        '''
        url = ' https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(self.corpid, self.secret)
        res = requests.get(url).json()
        return res['access_token']
